package cn.easier;
import com.google.gson.Gson;
import static spark.Spark.*;
import spark.Request;
import spark.Response;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.FileWriter;

//TIP 要<b>运行</b>代码，请按 <shortcut actionId="Run"/> 或
// 点击装订区域中的 <icon src="AllIcons.Actions.Execute"/> 图标。
public class Main {

    static final Gson gson = new Gson();

    public static void main(String[] args) {
        // 设置端口号
        port(9009);

        // GET请求，返回JSON
        get("/hello", (req, res) -> {
            res.type("application/json");
            return gson.toJson(new Message("Hello, World!"));
        });

        // POST请求，接收JSON并返回处理结果
        post("/videoTransf", "application/json", (req, res) -> {
            res.type("application/json");
            RegisterRequest request = gson.fromJson(req.body(), RegisterRequest.class);
            System.out.println("入参:");
            System.out.println(gson.toJson(req.body()));

            String containerId = getContainerId();

            System.out.println(containerId);
            Integer port = request.getPort();
            String portStr = String.format("%d", port); ;

            String msg = "success";

            if (port >= 41100 && port <= 41200) {

            }
            else
            {
                msg = "错误:port 不在 41100 ～ 41200 范围内";
            }

            String pushUrl = "rtmp://172.16.110.11:1935/live/" + containerId + "livestream"+ portStr;
            String logPath = "/data/app/xth/formal/dockerformallivestream" + portStr + ".log";
            String scriptPath = "/data/app/xth/formal/start_livestream.sh";

            try {
                // 设置脚本文件的可执行权限
                Process process = Runtime.getRuntime().exec("chmod +x " + scriptPath);
                process.waitFor(); // 等待命令执行完成
                System.out.println("Script permissions set successfully.");
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }

            runShellScript(scriptPath,portStr,pushUrl,logPath);

            RegisterResponse response = new RegisterResponse(request.getPort(),pushUrl,logPath,msg);

            System.out.println("出参:");
            System.out.println(gson.toJson(response));

            return gson.toJson(response);
        });

        // 启动服务器
        awaitInitialization();
    }

    public static boolean createShellScript(String scriptPath, String scriptContent) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(scriptPath))) {
            // 写入脚本内容
            writer.write(scriptContent);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String getContainerId() {
        String cgroupPath = "/proc/self/cgroup";
        try (BufferedReader reader = new BufferedReader(new FileReader(cgroupPath))) {
            String line;
            String containerId = "";
            while ((line = reader.readLine()) != null) {
                // 查找包含 "docker/" 的行
                if (line.contains("docker/")) {
                    // 提取容器 ID
                    int startIndex = line.lastIndexOf("docker/") + 7; // "docker/" 的长度为 7
                    int endIndex = line.length();
                    containerId = line.substring(startIndex, endIndex);
                    if (containerId != null && containerId.length() >= 12) {
                        containerId = containerId.substring(0, 12);
                    }

                    return containerId;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "1234567890";
    }

    public static void runShellScript(String scriptPath,String arg1,String arg2,String arg3) {
        try {
            // 定义要执行的 Shell 脚本和参数
            // 使用 ProcessBuilder 执行脚本并传递参数
            ProcessBuilder processBuilder = new ProcessBuilder(scriptPath,arg1,arg2,arg3);
            processBuilder.redirectErrorStream(true);
            // 启动进程
            Process process = processBuilder.start();
            // 获取脚本的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // 等待脚本执行完成
            int exitCode = process.waitFor();
            System.out.println("脚本执行完毕，退出码: " + exitCode);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class Message {
        String message;

        Message(String message) {
            this.message = message;
        }
    }

    static class RegisterRequest {
        Integer port;

        public Integer getPort() {
            return port;
        }
    }

    static class RegisterResponse {
        Integer port;

        String pushUrl;

        String logPath;

        String message;
        RegisterResponse(Integer port,String pushUrl,String logPath,String msg) {
            this.port = port;
            this.pushUrl = pushUrl;
            this.logPath = logPath;
            this.message = msg;
        }
    }

}